package com.diy.common.bussiness.service.defaultOperation;

import com.diy.common.bussiness.service.defaultService.Savable;
import com.diy.common.baseModel.BaseDiyBean;
import com.diy.common.baseModel.BaseDiyQueryParamsBean;
import com.diy.common.exception.ErrorCodeOfException;
import com.diy.common.exception.ProgramException;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by GY on 2015/11/22.
 */
public abstract class defaultBaseManagerHandler<T extends BaseDiyBean,P extends BaseDiyQueryParamsBean> implements Savable<T,P> {

    protected ErrorCodeOfException commonKeyMark = ErrorCodeOfException.PrivateKey;
    protected ErrorCodeOfException commonTableNameMark = ErrorCodeOfException.PrivateKey;

    /**
     * 参数校验，不正确则抛出异常，进行终止操作
     *
     * @param arg
     */
    protected void filterParams(P arg) {
        if (arg == null)
            throw new ProgramException(commonKeyMark.getDesc(), commonKeyMark.getCode());

        if (arg.getMapperName().isEmpty())
            throw new ProgramException(commonTableNameMark.getDesc(), commonTableNameMark.getCode());
    }

    //真正进行的逻辑处理事情
    protected abstract T saving(P arg);


    //保存或修改后，要执行的操作
    protected void saved(T t, P arg) {
    }

    @Transactional
    public final T save(P arg) {

        filterParams(arg);

        T resultT = saving(arg);

        saved(resultT, arg);

        return resultT;
    }
}